package com.itheima.controller;

import com.itheima.pojo.Result;
import com.itheima.util.AliyunOSSOperator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

@RestController
public class UpLoadController {
    @Autowired
    private AliyunOSSOperator aliyunOSSOperator;

    /*
        前端上传一张图片 , 后端会把文件存储到一个临时文件夹中
        当前方法执行完毕,临时文件会消失

        LTAI5tMCiRxjiJdynGB1mySc
        CnlUEyKJrkA7OIdZlae4FY723izA4A
        echo "export OSS_ACCESS_KEY_ID='LTAI5tMCiRxjiJdynGB1mySc'" >> ~/.zshrc
        echo "export OSS_ACCESS_KEY_SECRET='CnlUEyKJrkA7OIdZlae4FY723izA4A'" >> ~/.zshrc

     */
    @PostMapping("/upload")
    public Result upload(MultipartFile file) throws Exception {
//        // 获取文件原始名称
//        String originalFilename = file.getOriginalFilename(); /// "liqin01.jpeg"
//
//        // 扩展名
//        String[] strings = originalFilename.split("\\.");
//        String kzName = strings[strings.length - 1];
//
//        // 把临时文件保存本地
//        file.transferTo(new File("/Users/yangqixuan/Documents/develop/idea-project3/spring-web-project/img/" + UUID.randomUUID() + "." + kzName));

        // 获取文件原始名称
        String originalFilename = file.getOriginalFilename();
        // 上传文件对应的字节数组
        byte[] bytes = file.getBytes();

        // 把文件上传到阿里云服务
        String url = aliyunOSSOperator.upload(bytes, originalFilename);

        return Result.success(url);
    }
}
